package com.yaoli.ajob;

/**
 * Created by will on 2017/4/30.
 */
public class _059_SpiralMatrixII {
    public static void main(String[] args) {
        _059_SpiralMatrixII spiralMatrixII = new _059_SpiralMatrixII();

        int matrix [][] = spiralMatrixII.generateMatrix(10);

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j]+"\t");
            }
            System.out.println("");
        }
    }
    public int[][] generateMatrix(int n) {

        int matrix[][] = new int[n][n];
        if(n == 0){
            return matrix;
        }
        int index = 1;

        int brow = 0;
        int bcol = 0;
        int erow = matrix.length - 1;
        int ecol = matrix[0].length - 1;

        while(brow <= erow && bcol <= ecol){
            index = fill(matrix,brow,bcol,erow,ecol,index);
            brow ++;
            bcol ++;
            ecol --;
            erow --;
        }

        return matrix;
    }

    public int fill(int [][] matrix,int brow,int bcol,int erow,int ecol, int index){

        for(int i = bcol ; i <= ecol ; i++,index++){
            matrix[brow][i] = index;
        }

        for(int i = brow + 1 ; i <= erow ; i++,index++){
            matrix[i][ecol] = index;
        }

        for(int i = ecol - 1; i >= bcol ; i -- ,index++){
            matrix[erow][i] = index;
        }

        for(int i = erow - 1; i >brow ; i-- ,index++){
            matrix[i][bcol] = index;
        }

        return index;
    }
}
